import React, { useMemo, useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import SearchBar from '../components/SearchBar';
import AttractionCard from '../components/AttractionCard';
import { useNavigation, useRoute } from '@react-navigation/native';
import { locationAPI } from '../api';
import { ToastManager } from '../components/Toast';
import { EmptyState, LoadingIndicator } from '../components/common';
import { parseDistance } from '../utils/helpers';
import {
  COLORS,
  RADIUS,
  FONT_SIZE,
  FONT_WEIGHT,
  SPACING,
} from '../styles/constants';

export default function SearchScreen() {
  const navigation = useNavigation();
  const route = useRoute();
  const { city = '当前城市' } = route.params || {};
  const [query, setQuery] = useState('');
  const [sortBy, setSortBy] = useState('relevance'); // relevance | rating | distance
  const [recent, setRecent] = useState([]);
  const [loading, setLoading] = useState(false);
  const [resultsData, setResultsData] = useState([]);

  useEffect(() => {
    (async () => {
      const raw = await AsyncStorage.getItem('recent_search_keywords');
      if (raw) setRecent(JSON.parse(raw));
    })();
  }, []);

  async function saveRecent(keyword) {
    const val = keyword.trim();
    if (!val) return;
    const next = [val, ...recent.filter(k => k !== val)].slice(0, 8);
    setRecent(next);
    await AsyncStorage.setItem('recent_search_keywords', JSON.stringify(next));
  }

  const fetchResults = useCallback(async keyword => {
    const val = keyword?.trim();
    if (!val) {
      setResultsData([]);
      return;
    }
    try {
      setLoading(true);
      const resp = await locationAPI.searchScenicByKeyword(val);
      const rows = resp?.data?.data || resp?.data?.rows || resp?.data || [];
      setResultsData(Array.isArray(rows) ? rows : []);
    } catch {
      ToastManager.error('搜索失败，请稍后再试');
      setResultsData([]);
    } finally {
      setLoading(false);
    }
  }, []);

  const results = useMemo(() => {
    const base = resultsData || [];
    if (sortBy === 'rating')
      return [...base].sort((a, b) => (b.rating || 0) - (a.rating || 0));
    if (sortBy === 'distance') {
      return [...base].sort(
        (a, b) => parseDistance(a.distance) - parseDistance(b.distance),
      );
    }
    return base;
  }, [resultsData, sortBy]);

  useEffect(() => {
    fetchResults(query);
  }, [query, fetchResults]);

  const cardsData = useMemo(
    () =>
      results.map((item, index) => ({
        id: String(item.id || item.scenicAreaId || index),
        name: item.name || '-',
        image: item.image,
        address: item.address,
        rating: item.rating,
        level: item.level,
        type: item.typeName || item.type,
        distance: item.distance,
        raw: item,
      })),
    [results],
  );

  return (
    <View style={styles.container}>
      <View style={styles.searchRow}>
        <SearchBar
          value={query}
          onChange={setQuery}
          placeholder={`搜索${city}景点`}
          onSubmit={() => {
            saveRecent(query);
            fetchResults(query);
          }}
          autoFocus
          showCancel={query?.length > 0}
          onCancel={() => setQuery('')}
          clearable
          onClear={() => setQuery('')}
        />
      </View>

      <View style={styles.toolbar}>
        <Text style={styles.resultHint}>
          为你找到 {cardsData.length} 个结果
        </Text>
        <View style={styles.sortRow}>
          <TouchableOpacity onPress={() => setSortBy('relevance')}>
            <Text
              style={[
                styles.sortBtn,
                sortBy === 'relevance' && styles.sortActive,
              ]}
            >
              相关
            </Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSortBy('rating')}>
            <Text
              style={[styles.sortBtn, sortBy === 'rating' && styles.sortActive]}
            >
              评分
            </Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSortBy('distance')}>
            <Text
              style={[
                styles.sortBtn,
                sortBy === 'distance' && styles.sortActive,
              ]}
            >
              距离
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      {recent.length > 0 && !query && (
        <View style={styles.recentBox}>
          <Text style={styles.recentTitle}>最近搜索</Text>
          <View style={styles.recentRow}>
            {recent.map(k => (
              <TouchableOpacity
                key={k}
                style={styles.chip}
                onPress={() => setQuery(k)}
              >
                <Text style={styles.chipText}>{k}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      )}

      {loading ? (
        <LoadingIndicator text="正在搜索..." />
      ) : (
        <FlatList
          data={cardsData}
          keyExtractor={item => item.id}
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={results.length === 0 ? { flex: 1 } : undefined}
          renderItem={({ item }) => {
            const itemData = item.raw || item;
            const areaType = itemData.areaType || 1; // 默认为景区
            return (
              <AttractionCard
                item={item}
                onPress={() =>
                  navigation.navigate('AttractionDetail', {
                    attraction: itemData,
                    itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
                    itemId: itemData.id || itemData.scenicAreaId,
                    areaType: areaType,
                  })
                }
              />
            );
          }}
          ListEmptyComponent={
            <EmptyState
              icon="search-outline"
              title="没有找到相关景点"
              description="尝试更短的关键词或换个说法"
            />
          }
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.white,
  },
  searchRow: {
    marginTop: SPACING.md,
    marginHorizontal: SPACING.lg,
    flexDirection: 'row',
    alignItems: 'center',
  },
  resultHint: {
    marginTop: SPACING.md,
    marginBottom: SPACING.xs,
    marginHorizontal: SPACING.lg,
    fontSize: FONT_SIZE.sm,
    color: COLORS.text.placeholder,
  },
  toolbar: {
    marginTop: SPACING.sm,
    marginHorizontal: SPACING.lg,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  sortRow: { flexDirection: 'row', gap: SPACING.md },
  sortBtn: { fontSize: FONT_SIZE.sm, color: COLORS.text.quaternary },
  sortActive: { color: COLORS.status.info, fontWeight: FONT_WEIGHT.semibold },
  recentBox: { marginTop: 10, marginHorizontal: SPACING.lg },
  recentTitle: {
    fontSize: FONT_SIZE.sm,
    color: COLORS.text.placeholder,
    marginBottom: SPACING.sm,
  },
  recentRow: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.sm },
  chip: {
    paddingHorizontal: 10,
    paddingVertical: 6,
    backgroundColor: COLORS.background.secondary,
    borderRadius: RADIUS.round,
  },
  chipText: { fontSize: FONT_SIZE.sm, color: COLORS.text.tertiary },
});
